import { swaggerConfig } from "../../swaggerConfig"
import { IJson } from "../../interface/type"
import { SwResult } from "../../store/swResult"

const STATIC_DEF = "#/definitions/"

function findDefinition(ref: string, definitions: IJson): IJson {
  // console.log('查找列表对象', ref)
  const obj: IJson = {}
  if (!ref || ref === STATIC_DEF) {
    return obj
  }
  ref = ref.replace(STATIC_DEF, "")
  console.log('查找对象:', definitions[ref])
  const properties = definitions[ref]?.properties
  if (ref.indexOf('响应结果') > -1) {
    return findDefinition(properties.data.$ref, definitions)
  }
  // 必填字段
  const requiredPrams: string[] = definitions[ref]?.required ? definitions[ref]?.required : []
  for (const key of Object.keys(properties)) {
    const item = properties[key]
    obj[key] = item
    if (requiredPrams.indexOf(key) > -1 || item.required) {
      obj.isReq = true
    }
    if (item && (item.type === "array" || item.type === "object") && (!!item?.$ref || !!item?.items?.$ref)) {
      const refs = item?.$ref ? item.$ref : item?.items?.$ref
      console.log('查找下一层', refs)
      obj[key].children = findDefinition(refs, definitions)
    } else if (item && !item.type && item?.$ref) {
      console.log('查找下一层', item.$ref)
      obj[key].children = findDefinition(item.$ref, definitions)
    }
  }
  return obj
}

function getResult(apiName: string, sw: SwResult) {
  const paths = sw.getPaths()
  // pageConfig?.list?.apiName
  const item = paths[swaggerConfig.baseUrl + apiName]
  const json = item.post ? item.post : item.get
  const parameters = json.parameters
  const responses = json.responses['200']
  let parma: IJson = {}
  for (const it of parameters) {
    const obj = findDefinition(it?.schema?.$ref, sw.getDefinitions())
    // obj.isReq = it.required
    parma = Object.assign({}, parma, obj)
  }
  // console.log('接口入参：', parma)
  const res: IJson = findDefinition(responses.schema.$ref, sw.getDefinitions())
  // console.log('接口出参：', res)
  return {
    parameters: parma,
    responses: res
  }
}

export default {
  findDefinition,
  getResult
}
